<!DOCTYPE html>

<html>
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width initial-scale=1.0 user-scalable=0" />
    <link type="image/x-icon" rel="shortcut icon" href="/static/favicon.ico" />
    <title>手写识别2</title>
    <style>
        div{
            width: 366px;
            margin: 0 auto;
        }
        
        #display{
            padding:0;
            margin:0 auto 2px auto;
            border:1px; 
            border-style:dashed;
            
            height:110px;             
        }
        
        div[class="image-wrapper"]{
            margin:0;
            padding:0;
            border:0; 
            
            //display:inline; 

            height:40px;
            position: relative;
            left: 70px;
            
        }

        canvas{
            border:8px dashed rgba(255, 97, 3, 0.8);
            border-radius: 3px;
            background-color: rgba(255, 255, 255, 0.6);
        }

        .post{
            display: none;
        }
        body{
            background: url("static/favicon.png");
            background-size: 350px auto;
            background-repeat:repeat;
            margin: 0;
        }

        input[type="button"]{
            width: 116px;
            height: 56px;
            padding:0;
            border: 1px;
            border-radius: 10px;
            margin: 5px 0 5px 0;
            display: inline;

            color: rgb(100, 32, 240);
            font-size: 20px;

            background: rgb(255, 165, 0);
        }
        input[type="button"]:active{
            transform: translateY(5px);
        }
        
        #minus{
            padding:0;
            border: 0;
            margin: 0;
            
            display: inline;
            visibility: hidden;
            
            //width: 20px;
            //height: 20px;
            border-radius: 20px;
            
            background-color: #E00;
            
            position: absolute;
            top: 50px;
            
            -webkit-transition-duration: 0.4s;  //Safari
            transition-duration: 0.4s;
        }
        #minus:active{
            background-color: #CCC;
        }
        #minus:hover{
            background-color: #CCC;
        }
        
        p.prompt{
            margin: 0;
            padding: 0;
            border: 0;
            
            width: 70px;
            height: 40px;
            font-size:16px;
            font-weight:bold;
            
            color: #EEE;
            background-color: #888;
        }
        .result{
            margin: 0 ;
            //padding: 0 ;
            padding-left: 10px;
            padding-right: 10px;
            border: 0;
            
            display: inline;
            
            //width: 40px;
            height: 30px;
            
            font-size: 30px;
            font-weight: bold;
            text-align: center;
            
            position: absolute;
            //top: -5px;
            
            color: #00E;
            background-color: rgba(255, 255, 255, 0.8);
            
        }
        
    </style>
    <script>
        var RECOG_URL = "/recog2";
        var OFFSET_LEFT = 70;  //Offset related to the #prompt-box, this is an absolute value.
        var MAX_COUNT = 8;
        var img_count = 0;
        var lastX=0, lastY=0;
        var flag = false;
        var trajectory = new Array();  //trajectory point pos
        
        var request = new XMLHttpRequest();
        request.onreadystatechange = function (){
            var IMG_WH = 40  //image width and height
            if (request.status==200 && request.readyState==4){
                data = JSON.parse(request.responseText);
                
                img_count += 1;
                if (img_count >0){show_out_display();}
                
                //insert raw image
                var wrapper_raw = document.getElementById("image-raw-wrapper");
                
                var img = document.createElement("img");
                img.src = data["image-raw-url"] + "?t=" + Math.random();
                img.alt = "出错";
                img.style['background-color'] = "rgba(255,255,255,0.9)";
                img.style.width = IMG_WH + "px"; img.style.height = IMG_WH + "px";
                
                wrapper_raw.appendChild(img);
                
                //insert resampled tra
                var wrapper_tra = document.getElementById("image-tra-wrapper");
                var img = document.createElement("img");
                img.src = data["image-tra-url"] + "?t=" + Math.random();
                img.alt = "出错";
                img.style.width = IMG_WH + "px"; img.style.height.height = IMG_WH + "px";
                
                wrapper_tra.appendChild(img);
                
                //move the minus icon
                var minus = document.getElementById("minus");
                minus.style.left = minus.offsetLeft + IMG_WH + "px";
                
                //insert recignition result
                var wrapper_result = document.getElementById("result-wrapper");
                var result = document.createElement("p");
                var digit = document.createTextNode(data["digit"]);
                result.appendChild(digit);
                result.setAttribute("class", "result");
                result.style.left = (img_count - 1) * IMG_WH + "px";
                
                wrapper_result.appendChild(result);
            }    
        }

        
        function show_out_display(){
            //Show the prompt text out when they shold show out.
                        
            //show prompt
            var prompt_box = document.getElementById("prompt-box");
            prompt_box.style.display = "block";
            //prompt_box.style.left = prompt_box.parentNode.offsetLeft + OFFSET_LEFT + "px";
            
            //console.log(prompt_box.parentNode.offsetLeft);
            
            //show minus
            var minus = document.getElementById("minus");
            minus.style.visibility = "visible";
        }
        function hide_display(){
            //hide minus
            var minus = document.getElementById("minus");
            minus.style.visibility = "hidden";
        }
                
        
        function draw(event){
            var pos = get_canvas_pos(event);
            var x = pos[0], y = pos[1];

            if (flag==false){
                //pause or go
                return 0;
            }
            else if (lastX == 0 && lastY == 0) {
                // skip the initial pos
                lastX = x;
                lastY = y;
                return 0;
            }

            var cvn = document.getElementById("cv");
            var ctx = cvn.getContext("2d");

            ctx.lineWidth = 20;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';

            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(x, y);
            ctx.stroke();

            lastX = x;
            lastY = y;
        }

        
        function view_pos(event){
            //dis = document.getElementById("dis");
            cvs = document.getElementById("cv");  //get the canvas
            //dis.value = "x:"+event.pageX.toFixed(0) + " y:"+event.pageY.toFixed(0);
            //dis.value += "; offset:"+cvs.offsetLeft + "," + cvs.offsetTop;
            //dis.value += "; flag:"+flag
        }

        
        function get_canvas_pos(event){
            var sx = event.pageX, sy = event.pageY;  //screen x, screen y
            var cvs = document.getElementById("cv");
            var x = cvs.offsetLeft, y = cvs.offsetTop;
            x = sx - x;
            y = sy - y;

            var pos = new Array(x, y);

            return pos;
        }

        
        function go(){
            flag = true;
        }
        function pause(){
            flag = false;
            lastX = lastY = 0; //restart to initial Pos
        }

        
        function collect_trajectory(evt){
            if (flag){
            pos = get_canvas_pos(evt);
            trajectory[trajectory.length] = pos[0];
            trajectory[trajectory.length] = pos[1];
            }
        }

    
        function handle_move(evt){
            //handle the touch move and mouse move event
            draw(evt);
            collect_trajectory(evt);
        }
        
        
        function touch_wrapper(){
            function touch(evt){
                evt.preventDefault()

                view_pos(evt.touches[0]);
                handle_move(evt.touches[0]);
                }
            return touch;
            }

        
        function get_data(){
            //get the relative data that is going to send to server.
            var data = new Object();  //This object is going to be converted to a json string.
            
            //wrap image
            var cvs = document.getElementById("cv");
            data.image = cvs.toDataURL("image/png");  // get a Data URL(I don't know what's it) and png file in base64 string
            
            //wrap trajectory
            var SEP = ",";
            var coordinates = "";  //coordinates = 坐标值们
            for (var i=0; i<trajectory.length; i++){
                coordinates = coordinates + trajectory[i] + SEP;
            }
            data.trajectory = coordinates;
            return data;
        }
        
        
        function reset_and_clear(){
            // reset the trajectory points records and clear canvas , 
            //therefore we are ready to recongnize the next digit.
            trajectory = new Array();
            var cvs = document.getElementById("cv");
            var ctx = cvs.getContext("2d");
            ctx.fillstyle = "rgba(0,0,0,0)";
            ctx.clearRect(0,0,1000,1000); //x,y,width,height,
        }
            
            
        function send_trajectory(){
            var data = get_data();
            reset_and_clear();
            
            var form = new FormData();
            form.append("image", data.image);
            form.append("trajectory", data.trajectory);
                        
            request.open("POST", RECOG_URL, true);
            //request.setRequestHeader("Content-Type", "text/plain")
            request.send(form); 
        }
        
        
        function init_mobile(){
            var cvs = document.getElementById("cv");
            cvs.addEventListener("touchmove", touch_wrapper(), false);
            cvs.addEventListener("touchstart", go, false);
            cvs.addEventListener("touchend", pause, false);
        }
        function init_minus(){
            var cvs = document.getElementById("minus");
            var ctx = cvs.getContext("2d");
            ctx.strokeStyle = "rgba(0,0,0)";
            //ctx.fillRect(0,0,10,10);
            
            var gap = 3;  // the gap to the border of the line
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.moveTo(gap, 10);
            ctx.lineTo(20-gap, 10);
            ctx.stroke();
            
            //set initial position
            cvs.style.left = cvs.parentNode.offsetLeft + OFFSET_LEFT + 3 + "px";  // the constant 3 acts like margin-left
        }
        function init(){
            init_mobile();
            init_minus();
        }
        
        
        function remove_result_and_image(){
            //remove the last result and images in the wrapper
            var wrapper = document.getElementById("image-raw-wrapper");
            wrapper.removeChild(wrapper.lastChild);
            
            var wrapper = document.getElementById("image-tra-wrapper");
            wrapper.removeChild(wrapper.lastChild);
            
            var wrapper = document.getElementById("result-wrapper");
            wrapper.removeChild(wrapper.lastChild);
            
            var minus = document.getElementById("minus");
            minus.style.left = minus.offsetLeft - 40 + "px";
            img_count -= 1;
            if (img_count == 0 ){
                minus.style.visibility = "hidden";
            }
        }
        
        
    </script>
</head>

<body onload="init()" onmousedown="go()" onmouseup="pause()">
    
    <div id="display" >
        <div id="prompt-box" style="height:80px;margin:0; border:0; padding:0; display:none; position:absolute;">
            <p class="prompt">原始图片:</p>
            <p class="prompt">重采样:</p>
            <p class="prompt" style="height:30px;">识别结果:</p>
        </div>
        <div id="image-raw-wrapper" class="image-wrapper" > </div>
        <div id="image-tra-wrapper" class="image-wrapper" style=""> </div>
        <div id="result-wrapper" style="margin:0; border:0; padding:0; position:relative; left:70px;"> </div>
        <canvas id="minus" width="20px" height="20px" onclick=remove_result_and_image() > </canvas>
    </div>


    <div onmousemove="handle_move(event)" >
        <canvas id="cv" width="350" height="350">
            你的浏览器不支持html5画布。
        </canvas>
    </div>

    
    <div style="width:237px">
        <form id="post-form" action="/" enctype="text/plain" method="POST">
            <!--这两个input标签原来是利用表单的机制，达到以POST方法上传image和trajectory目的，
            但是现在改用ajax和FormData对象上传表单，所以这两个
            元素就用不着了，也把按钮由type="submit"改成type="button"了。-->
            <input class="post" id="img" name="image" />
            <input class="post" id="trajectory" name="trajectory" />
            <input id="clear" type="button" value="重写" onclick=reset_and_clear() />
            <input id="submit" type="button" value="识别" onclick="send_trajectory()"/>
        </form>
    </div>

    <div style="text-align:center;">
        <style>
            a[href="/recog"]{
                padding: 2px;
                text-decoration: none;
                text-align: center;
                font-size: 16px;

                border: 1px;
                border-radius: 5px;

                color: rgb(100, 32, 240);
                background: rgb(255, 165, 0);
            }
        </style>
        <a href="/recog" > 使用图片识别 </a>
    </div>
</body>
</html>